﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Core.Validation;
using System.ComponentModel;
using Kingdee.BOS.App;
using Kingdee.BOS.Contracts;
using Kingdee.K3.BD.Contracts;
using Kingdee.BOS.App.Data;

namespace K.KDL
{
    [Description("采购收料单-保存操作")]
    public class CustomPurReceiveBillSaveOperationPlugin : AbstractOperationServicePlugIn
    {
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            //e.FieldKeys.Add(""); 将需要应用的字段Key加入

            e.FieldKeys.Add("FDate");
            e.FieldKeys.Add("FSupplierId");
        }

        /// <summary>
        /// 添加校验器
        /// </summary>
        /// <param name="e"></param>
        public override void OnAddValidators(AddValidatorsEventArgs e)
        {
            var operValidator = new OperValidator();
            operValidator.AlwaysValidate = true;
            operValidator.EntityKey = "FBillHead";
            e.Validators.Add(operValidator);
        }

        /// <summary>
        /// 操作开始前功能处理
        /// </summary>
        /// <param name="e"></param>
        public override void BeginOperationTransaction(BeginOperationTransactionArgs e)
        {
            RefreshLotInfo(e);
        }

        void RefreshLotInfo(BeginOperationTransactionArgs e)
        {
            var dbService = ServiceHelper.GetService<IDBService>();
            var cvtService = ServiceHelper.GetService<IUnitConvertService>();
            var entities = e.DataEntitys;
            foreach (var entity in entities)
            {
                var lines = entity["PUR_ReceiveEntry"] as DynamicObjectCollection;
                if (lines == null || lines.Count() == 0)
                {
                    continue;
                }

                var id = Convert.ToInt32(entity["Id"]);
                
                foreach (var line in lines)
                {
                    var lotNumber = line["F_PATC_JHPH"];
                    if (lotNumber != null && lotNumber.ToString().Trim().Length>0)
                    {
                        //T_PUR_Receive。找fid不是当前的其它单据，如果其它单据中有相同进货批号，抛出异常
                        var sql2 = @"/*dialect*/SELECT COUNT(1) AS CNT FROM T_PUR_ReceiveEntry where F_PATC_JHPH='{0}' and FID!='{1}'";
                        var row2 = DBUtils.ExecuteDynamicObject(Context, string.Format(sql2, lotNumber.ToString().Trim(), id)).First();
                        if (Convert.ToInt32(row2[0]) > 0)
                        {
                            throw new Exception("进货批号" + lotNumber + "有重复!");
                        }
                    } 
                }
                
            }
        }

        /// <summary>
        /// 操作结束后功能处理
        /// </summary>
        /// <param name="e"></param>
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            foreach (DynamicObject o in e.DataEntitys)
            {
            }
        }

        /// <summary>
        /// 当前操作的校验器
        /// </summary>
        private class OperValidator : AbstractValidator
        {
            public override void Validate(Kingdee.BOS.Core.ExtendedDataEntity[] dataEntities, ValidateContext validateContext, Kingdee.BOS.Context ctx)
            {
                //foreach (var dataEntity in dataEntities)
                //{
                //判断到数据有错误
                //    if()
                //    {
                //        ValidationErrorInfo ValidationErrorInfo = new ValidationErrorInfo(
                //            string.Empty,
                //            dataEntity["Id"].ToString(),
                //            dataEntity.DataEntityIndex,
                //            dataEntity.RowIndex,
                //            dataEntity["Id"].ToString(),
                //            "errMessage",
                //             string.Empty);
                //        validateContext.AddError(null, ValidationErrorInfo);
                //        continue;
                //    }

                //}
            }
        }
    }
}
